<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\Areainfo;
use App\Model\DistributionCenter;
use App\Model\Industry;
use App\Model\LinkIndustry;
use App\Service\DistributionCenterService;
use App\Service\SpecialtyService;
use Hyperf\Validation\Rule;
use Hyperf\DbConnection\Db;
Use Hyperf\Di\Annotation\Inject;

class DistributionCenterController extends AbstractController
{



    public function list()
    {
        // 关键字：行业名称
        $key_word = $this->request->input('key_word', '');
        $is_show = $this->request->input('is_show', '');
        $ids = $this->request->input('ids', []);
        $area_id = $this->request->input('area_id', '');

        $fields = ['*'];
        $center = New DistributionCenter();
        $where = [];
        if($is_show!=''){
            $where['is_show'] = $is_show;
        }
        if($key_word!=''){
            $where[] = ['name', 'like', '%' . $key_word . '%'];
        }

        if($area_id!=''){
            $level_set = ['2'=>'province_id','3'=>'city_id','4'=>'area_id','5'=>'street_id'];
            $area_info = (New Areainfo())->find($area_id);
            if(!$area_info){
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID, '不存在的地区id');
            }else{
                $level  =   $area_info->level;
                $where[$level_set[$level]] = $area_id;
            }
        }

        $center_ids = [];
        if (!empty($ids)) {
           $center_ids =  LinkIndustry::query()->where('type',1)->whereIn('industry_id',$ids)->pluck('link_id');
        }
        $list = [];
        $union1 = $center->where('is_country',1)->select($fields);
        $count =$center
            ->where($where)
            ->when($ids,function ($query) use ($center_ids){
                $query->whereIn('id',$center_ids);
            })
            ->union($union1)
            ->count();
        if($count>0){
            $center_model = $center
                ->where($where)
                ->when($ids,function ($query) use ($center_ids){
                    $query->whereIn('id',$center_ids);
                })
                ->union($union1)
                ->with(['create_info','update_info','province','city','area','street','file_info','link_industry','link_tags','link_honors','link_files'])
                ->orderBy('is_country','desc')
                ->orderBy('id','desc')
                ->select($fields);
            $list = $this->paginate($center_model);
        }
//        $return = [
//            'list' => $list,
//        ];
        return $this->jsonResponse->success($list, '获取列表成功');
    }


    public function add(DistributionCenterService $center)
    {

        $params = $this->request->inputs(['name','province_id','city_id','area_id','street_id',
            'is_home_page','fileinfo_id','tips','fileinfo_ids','description','industry','tags','honors'
            ,'is_country'
        ]);
        $this->validation(
            $params,
            [
                'name' => [
                    "required",
                    "string",
                    "max:50",
                    Rule::unique('fly_distribution_center','name')->whereNull('deleted_at'),
                ],
                'province_id' => [
                    "integer",
                    "min:0",
                    Rule::exists('areainfo','id')->where('level',2),
                ],
                'city_id' => [
                    "integer",
                    "min:0",
                    Rule::exists('areainfo','id')->where('level',3),
                ],
                'area_id' => [
                    "integer",
                    "min:0",
                    Rule::exists('areainfo','id')->where('level',4),
                ],
                'street_id' => [
                    "integer",
                    "min:0",
                    Rule::exists('areainfo','id')->where('level',5),
                ],
                'description' => 'string|max:50',
                'industry' => "required|array|min:1",
                'industry.*' => [
                    "required",
                    "distinct",
                    "integer",
                    "min:0",
                    Rule::exists('fly_industry','id')->whereNull('deleted_at'),
                ],
                'is_home_page' => 'required|boolean',
                'is_country' => 'required|boolean',
                'fileinfo_id' => [
                    Rule::requiredIf($params['is_home_page']==1),
                    "exists:fileinfo,fileinfo_id",
                    "min:0",
                ],
                'fileinfo_ids.*' => 'integer|min:1|distinct|exists:fileinfo,fileinfo_id',
                'tags' => "required|array|min:1",
                'tags.*' => "required|string|max:50",
                'honors' => "array",
                'honors.*' => "string|max:50",
            ],
            );
        Db::beginTransaction();
        $admin_id =  parent::getAdminId();
        $params['created_at'] = date('Y-m-d H:i:s');
        $params['create_by'] = $admin_id;
        try{
            if($center->insert($params)){
                Db::commit();
                return $this->jsonResponse->success([],'添加成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败请检查');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败：'.$exception->getMessage());
        }
    }

    public function edit(DistributionCenterService $center)
    {
        $params = $this->request->inputs(['id','name','province_id','city_id','area_id','street_id','tips',
            'is_home_page','fileinfo_id','fileinfo_ids','description','industry','tags','honors'
            ,'is_country'
        ]);
        $this->validation(
            $params,
            [
                'id' => [
                    "required",
                    "integer",
                    "min:1",
                    Rule::exists('fly_distribution_center','id')->whereNull('deleted_at')
                ],
                'name' => [
                    "required",
                    "string",
                    "max:50",
                    Rule::unique('fly_distribution_center','name')->whereNull('deleted_at')->ignore($params['id']),
                ],
                'province_id' => [
                    "integer",
                    "min:0",
                    Rule::exists('areainfo','id')->where('level',2),
                ],
                'city_id' => [
                    "integer",
                    "min:0",
                    Rule::exists('areainfo','id')->where('level',3),
                ],
                'area_id' => [
                    "integer",
                    "min:0",
                    Rule::exists('areainfo','id')->where('level',4),
                ],
                'street_id' => [
                    "integer",
                    "min:0",
                    Rule::exists('areainfo','id')->where('level',5),
                ],
                'description' => 'string|max:50',
                'industry' => "required|array|min:1",
                'industry.*' => [
                    "required",
                    "distinct",
                    "integer",
                    "min:0",
                    Rule::exists('fly_industry','id')->whereNull('deleted_at'),
                ],
                'is_home_page' => 'required|boolean',
                'is_country' => 'required|boolean',
                'fileinfo_id' => [
                    Rule::requiredIf($params['is_home_page']==1),
                    "exists:fileinfo,fileinfo_id",
                    "min:0",
                ],
                'fileinfo_ids.*' => 'integer|min:1|distinct|exists:fileinfo,fileinfo_id',
                'tags' => "required|array|min:1",
                'tags.*' => "required|distinct|string|max:50",
                'honors' => "array",
                'honors.*' => "string|distinct|max:50",
            ],
            );
        Db::beginTransaction();
        $admin_id =  parent::getAdminId();
        $params['updated_at'] = date('Y-m-d H:i:s');
        $params['update_by'] = $admin_id;
        try{
            if($center->update($params)){
                Db::commit();
                return $this->jsonResponse->success([],'修改成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败请检查');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败：'.$exception->getMessage());
        }
    }

    public function detail()
    {
        $id = $this->request->input('id');
        $this->validation(
            ['id'=>$id],
            [
                'id' => [
                    'required',
                    'integer',
                    'min:0',
                    Rule::exists('fly_distribution_center','id')->whereNull('deleted_at')
                ],
            ],
            );
        try{
            $info =  (New DistributionCenter())
                ->with(['create_info','update_info','province','city','area','street','file_info','link_industry','link_tags','link_honors','link_files'])
                ->find($id);
            return $this->jsonResponse->success($info,'信息返回');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'不存在或已删除：'.$exception->getMessage());
        }

    }

    /**
     * @param DistributionCenterService $center
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function del(DistributionCenterService $center)
    {
        $ids = $this->request->input('ids');
        $this->validation(
            ['ids'=>$ids],
            [
                'ids' => 'required|array|min:1',
                'ids.*' => [
                    'required',
                    'integer',
                    'min:0',
                    Rule::exists('fly_distribution_center','id')->whereNull('deleted_at'),
//                     //todo 需要验证没有关联的数据表
//                    Rule::unique('fly_distribution_center','project_id')->where(function ($query) {
//                        $query->where('tenant_id',$tenantId)
//                            ->whereNull('deleted_at');
//                    }),
                ],
            ],
            [
                'ids.*.unique'  =>'有关联数据，不可删除',
            ]

        );
        try{
            $center->deleteByUser($ids,$this->getAdminId(),1);
            return $this->jsonResponse->success([],'删除成功');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'删除失败');
        }

    }

    /**
     * @param DistributionCenterService $center
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function change_show(DistributionCenterService $center)
    {
        $ids = $this->request->input('ids');
        $is_show = $this->request->input('is_show');
        $this->validation(
            [
                'ids'=>$ids,
                'is_show'=>$is_show
            ],
            [
                'is_show' => 'required|boolean',
                'ids' => 'required|array',
                'ids.*' => [
                    'required',
                    'integer',
                    'min:0',
                    Rule::exists('fly_distribution_center','id')->whereNull('deleted_at')
                ],
            ],
            );
        try{
            $center->change_show($ids,boolval($is_show),$this->getAdminId());
            return $this->jsonResponse->success([],'修改成功');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败:'.$exception->getMessage());
        }

    }

}